package com.ff.neuropp.jwt;

import com.ff.neuropp.domain.Auth;
import com.ff.neuropp.domain.Role;
import com.ff.neuropp.domain.User;
import com.ff.neuropp.service.UserService;
import com.ff.neuropp.util.RequiredPermission;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

public class SecurityInterceptor implements HandlerInterceptor {

    @Resource
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 验证权限
        if(request.getMethod().equals("OPTIONS") ){
            return true;
        }
        String url = request.getServletPath(); // error
        if (isWhiteListUrl(url)) {
            return true;
        }
        String token = request.getHeader("token");
        String account = "";
        if (token != null && token.length() > 0) {
            account = JwtHelper.parseToken(token);
        }
        if (account.equals("") && !url.equals("/api/user/login")) {
            response.sendError(HttpStatus.FORBIDDEN.value(), "无权限");
            return false;
        }
        if (this.hasPermission(handler, account)) {
            return true;
        }
        // 如果没有权限 则抛403异常 springboot会处理，跳转到 /error/403 页面
        response.sendError(HttpStatus.FORBIDDEN.value(), "无权限");
        return false;
    }

    /**
     * 是否有权限
     *
     * @param handler
     * @return
     */
    private boolean hasPermission(Object handler, String account) {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            // 获取方法上的注解
            RequiredPermission requiredPermission = handlerMethod.getMethod().getAnnotation(RequiredPermission.class);
            // 如果方法上的注解为空 则获取类的注解
            if (requiredPermission == null) {
                requiredPermission = handlerMethod.getMethod().getDeclaringClass().getAnnotation(RequiredPermission.class);
            }
            // 如果标记了注解，则判断权限
            if (requiredPermission != null && StringUtils.isNotBlank(requiredPermission.value())) {
                // redis或数据库 中获取该用户的权限信息 并判断是否有权限
                User user = userService.findUserByAccount(account);
                if (null == user) {
                    return false;
                }
                Role role = user.getRole();
                List<String> auths = new ArrayList<>();
                List<Auth> authList = role.getAuths();
                if (null != authList && authList.size() > 0) {
                    for (Auth auth : authList) {
                        auths.add(auth.getUrl());
                    }
                }

                if (null == auths || (null != auths && auths.size() == 0)) {
                    return false;
                }
                if (auths.contains(requiredPermission.value())) {
                    return true;
                } else {
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // TODO
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // TODO
    }

    private boolean isWhiteListUrl(String url) {
        if (url.equals("/api/user/login") || url.equals("/api/user/logout") || url.equals("/api/user/getverify") || url.contains("/api/excel/import")
                || url.equals("/api/file/uploadfile")|| url.equals("/api/file/getimg")|| url.equals("/api/question/create")
                || url.equals("/api/schooldata/getschooltype") || url.equals("/api/school/list") || url.equals("/api/schooldata/listbytype")
                || url.equals("/api/questionnaire/findbyid") || url.equals("/api/questionnaire/submit") || url.equals("/api/school/list") || url.equals("/api/school/updateschoolData")
                || url.startsWith("/swagger") || url.startsWith("/webjars/springfox-swagger-ui") || url.equals("/v2/api-docs") || url.startsWith("/upload") || url.startsWith("/app") || url.startsWith("/api/file")) {
            return true;
        }else {
            return false;
        }

    }
}
